import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import viteSvgIcons from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'
import viteCompression from 'vite-plugin-compression'
import path from 'path'
import externalGlobals from 'rollup-plugin-external-globals'
import loadBaseUrl from './build/loadBaseUrl.js'

const baseUrl = loadBaseUrl()

// https://vitejs.dev/config/
export default ({ command, mode }) => {
  console.log(command)
  return defineConfig({
    base: mode === 'development' ? '/' : './',
    plugins: [
      vue({
        // 用于支持$ref
        refTransform: true
      }),
      AutoImport({
        // 增加此配置之后就不需要再.vue页面中写import { ref, ... } from 'vue';了
        imports: ['vue', 'vue-router'],
        eslintrc: {
          enabled: false, // Default `false`
          filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        }
      }),
      Components({
        resolvers: [AntDesignVueResolver()]
      }),
      viteSvgIcons({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]'
      }),
      viteMockServe({
        // default
        mockPath: 'mock',
        localEnabled: command === 'serve',
        supportTs: false,
        // localEnabled: false,
        prodEnabled: true,
        injectCode: `
          import setupProdMockServer from './mockProServer';
          setupProdMockServer();
        `
      }),
      // gzip
      viteCompression()
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src')
      }
    },
    server: {
      host: true,
      port: 8088,
      proxy: {
        [baseUrl]: {
          target: 'http://10.40.147.5:7001',
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${baseUrl}`), '')
        }
      }
    },
    optimizeDeps: {
      include: ['element-plus', 'axios', 'lodash-es']
    },
    build: {
      rollupOptions: {
        // external: ['axios'],
        // plugins: [
        //   externalGlobals({
        //     // vue: "Vue",
        //     axios: 'axios'
        //   })
        // ],
        output: {
          manualChunks(id) {
            // console.log(id)
            if (id.includes('node_modules')) {
              console.log(id)

              console.log(' >>> ', id.toString().split('node_modules/')[1].split('/')[0].toString())
              return 'vendor'
            }
          }
        }
      }
    }
  })
}
